<template>
  <div>
    <el-badge v-if="notificationsNumber>0 || notificationsNumber=='99+'" :value="notificationsNumber" style="line-height: 25px;">
      <router-link to="/notice/index">
        <svg-icon icon-class="message" />
      </router-link>
    </el-badge>
    <router-link v-else to="/notice/index">
      <svg-icon icon-class="message" />
    </router-link>
  </div>
</template>

<script>
import { current } from '@neu/biz-core/api/notice'
import { update } from '@neu/biz-core/api/notice'
export default {
  name: 'Notice',
  data() {
    return {
      notification: null
    }
  },
  computed: {
    notificationsNumber() {
      const notification = this.$store.getters.notifications.notification
      if (notification !== null) {
        this.showNotification(notification)
      }
      return this.$store.getters.notifications.number > 99 ? '99+' : this.$store.getters.notifications.number
    }
  },
  mounted() {
    current().then(res => {
      const data = res.data
      this.$store.dispatch('notice/initNotification', data)
    })
  },
  methods: {
    showNotification(notification) {
      this.notification = notification
      const content = '<div title="' + notification.content + '">' + (notification.content.length > 65 ? notification.content.substring(0, 65) + '...' : notification.content) + '</div>'
      this.$notify.success({
        title: notification.title,
        dangerouslyUseHTMLString: true,
        message: content,
        position: 'bottom-right',
        showClose: true,
        duration: 3000,
        onClick: this.clickNotification
      })
      if (notification === this.$store.getters.notifications.notification) {
        this.$store.dispatch('notice/resetNotification')
      }
    },
    clickNotification() {
      this.notification.isRead = 'read'
      update(this.notification.id, this.notification).then(res => {
        // 被点击的这条消息状态设置为已读
      })
      if (this.notification.noticeRoute) {
        this.$router.push({ name: this.notification.noticeRoute, params: JSON.parse(this.notification.businessInfo) })
      } else {
        this.$router.push({ name: 'notice' })
      }
    }
  }
}
</script>
